package main

import (
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
	"golang.org/x/net/context"
	"io"
	"log"
	"math/rand"
	"net/http"
	"strconv"
)

func rolldice(w http.ResponseWriter, r *http.Request) {
	roll := 1 + rand.Intn(6)

	testContext()
	log.Printf("Rolled a %d\n", roll)
	resp := strconv.Itoa(roll) + "\n"
	if _, err := io.WriteString(w, resp); err != nil {
		log.Printf("Write failed: %v\n", err)
	}
}

func main() {
	http.HandleFunc("/rolldice", rolldice)

	log.Fatal(http.ListenAndServe(":8080", nil))
}

func testContext() {
	tracer := otel.Tracer("app-tracer")
	opts := append([]trace.SpanStartOption{}, trace.WithSpanKind(trace.SpanKindServer))
	rootCtx, rootSpan := tracer.Start(context.Background(), getRandomSpanName(), opts...)
	if !rootSpan.SpanContext().IsValid() {
		panic("invalid root span")
	}
	go func() {
		opts1 := append([]trace.SpanStartOption{}, trace.WithSpanKind(trace.SpanKindInternal))
		_, subSpan1 := tracer.Start(rootCtx, getRandomSpanName(), opts1...)
		defer func() { subSpan1.End() }()
	}()
	go func() {
		opts2 := append([]trace.SpanStartOption{}, trace.WithSpanKind(trace.SpanKindInternal))
		_, subSpan2 := tracer.Start(rootCtx, getRandomSpanName(), opts2...)
		defer func() { subSpan2.End() }()
	}()
	rootSpan.End()
}

func getRandomSpanName() string {
	return strconv.Itoa(rand.Intn(1024))
}
